package com.alit.ibot.robot.wechat.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alit.ibot.robot.projectvariable.PVK;
import com.alit.ibot.robot.projectvariable.PVU;
import com.alit.ibot.robot.wechat.data.RobotMessageType;
import com.alit.ibot.robot.wechat.data.WechatMessageType;
import com.alit.ibot.robot.wechat.service.AttachmentService;
import com.alit.ibot.robot.wechat.service.RobotWechatCommonService;
import com.alit.ibot.robot.wechat.util.TransferUtil;
import com.alit.ibot.robot.wechat.util.WechatCutomerUtil;
import com.alit.ibot.robot.wechat.util.WechatUploadUtil;
import com.alit.ibot.robot.wechat.util.WechatXMLUtil;
import com.litong.utils.ibot.robot.AskRequest;
import com.litong.utils.ibot.robot.AskResponse;
import com.litong.utils.ibot.robot.AttachmentUtil;
import com.litong.utils.ibot.robot.CommandsBean;
import com.litong.utils.ibot.robot.RobotHttpClient;

import lombok.extern.slf4j.Slf4j;

/**
 * @author litong
 * @date 2019年5月31日_下午9:03:59
 * @version 1.0
 * @desc
 */
@Service
@Slf4j
public class RobotWechatCommonServiceImpl implements RobotWechatCommonService {
  @Autowired
  private AttachmentService attachmentService;
  private String errorMsg1 = "从服务器发送转人工消息到微信平台失败,1、检查是否通过微信认证 。2、检查https://mp.weixin.qq.com->开发->接口权限->客服接口是否开通。";

  public String beforeRequestRobot(Map<String, String> requestMap, String question) {
    String retval = this.processInstructions(requestMap, question); // 消息处理前的指令处理
    if (retval != null && !retval.equals("")) {
      String wechatTextXML = WechatXMLUtil.toWechatTextXML(requestMap, retval);
      log.info("处理指令:" + question + "返回数据:" + wechatTextXML);
      return wechatTextXML;
    }

    if (TransferUtil.isTransfer(question)) {// 转人工
      String jsonStirng = WechatCutomerUtil.sendText(requestMap, "正为你分配坐席");
      JSONObject resultObject = JSON.parseObject(jsonStirng);
      if (resultObject.getInteger("errcode") == 48001) {
        log.error(errorMsg1);
        return WechatXMLUtil.toWechatTextXML(requestMap, jsonStirng + errorMsg1);
      } else {
        Document dom = WechatXMLUtil.initToUserNameAndFromUserNameAndCreateTimeAndMsgType(requestMap,
            WechatMessageType.tcs);
        return WechatXMLUtil.domToString(dom);
      }
    }
    return null;
  }

  /**
   * 文本消息前置处理
   * 
   * @param requestMap
   * @return
   */
  private String processInstructions(Map<String, String> requestMap, String question) {
    if ((question != null)) {
      if ("test".equals(question)) {
        return "test success";
      } else if ("test_a_tag_1".equals(question)) { // 返回找链接格式
        return "<a href=\"http://www.baidu.com\">百度</a>";
      } else if ("test_a_tag_2".equals(question)) {
        return "【<a href=\"http://www.uairobot.com\">我的礼包</a>】";
      } else if ("test_a_tag_3".equals(question)) {
        return "【<a target=\"_blank\" href=\"http://www.uairobot.com\">我的礼包</a>】";
      } else if ("test_a_tag_4".equals(question)) {
        return "<HTML>【<a href=\"http://www.uairobot.com\">我的礼包</a>】</HTML>";
      } else if ("test_a_tag_5".equals(question)) {
        String content = "<HTML>【<a target=\"_blank\" href=\"http://www.uairobot.com\">我的礼包</a>】</HTML>";
        content = content.replace("<HTML>", "");
        content = content.replace("</HTML>", "");
        content = content.replace(" target=\"_blank\"", "");
        return content;
      } else if ("test_br_tag_1".equals(question)) {
        return "酒驾\n酒驾是";
      }
    }

    return null;
  }

  @Override
  public String getRobotContentAndConvertToWechatXML(Map<String, String> requestMap, String question) {
    String result = beforeRequestRobot(requestMap, question);
    if (result != null) {
      return result;
    }
    String robotURLInternal = PVU.getValue(PVK.robotURLInternal);
    AskRequest askRequest = new AskRequest();
    askRequest.setFormat("json");
    askRequest.setPlatform("weixin");
    askRequest.setQuestion(question);
    askRequest.setUserId(requestMap.get("FromUserName"));
    AskResponse robotReponse = RobotHttpClient.ask(robotURLInternal, askRequest);
    robotReponse.setContent(preProcessContent(robotReponse.getContent()));
    // 一共有4中消息类型,图片,图文,视频,音乐,文本,附件 其中文本,附件和附件没有明确标识
    if (robotReponse.getType() == 0) { // 默认回复
      return WechatXMLUtil.toWechatTextXML(requestMap, replaceContent(robotReponse.getContent()));
    }
    List<CommandsBean> commands = robotReponse.getCommands();
    for (CommandsBean c : commands) {
      String name = c.getName();
      if (name.equals(RobotMessageType.imgmsg)) { // 图片消息
        return processRobotImg(requestMap, c.getArgs());
      } else if (name.equals(RobotMessageType.imgtxtmsg)) { // 图文消息
        return processRobotImgtxt(requestMap, c.getArgs());
      } else if (name.equals(RobotMessageType.musicmsg)) { // 音乐消息
        return processRobotMusic(requestMap, c.getArgs());
      } else if (name.equals(RobotMessageType.videomsg)) { // 视频消息
        return processRobotVideo(requestMap, c.getArgs());
      }
    }

    String content = robotReponse.getContent();
    boolean isAttachment = AttachmentUtil.isAttachment(content);

    if (isAttachment) {
      //log.info("content中包括附件,开始处理" + content);
      content = attachmentService.index(content);
      //log.info("附件处理完成:" + content);
    }
    String xml = WechatXMLUtil.toWechatTextXML(requestMap, replaceContent(content));
    return xml;
  }

  /**
   * 预处理content的内容
   */
  private String preProcessContent(String content) {
    content = content.replace("<HTML>", "");
    content = content.replace("</HTML>", "");
    content = content.replace(" target=\"_blank\"", "");
    content = content.replace("<br>", "\n");
    return content;
  }

  private String replaceContent(String content) {
    String cnName = PVU.getValue(PVK.robotNameCN);
    String enName = PVU.getValue(PVK.robotNameEN);
    content = content.replace("xiaoi", enName);
    content = content.replace("小I", cnName);
    content = content.replace("小i", cnName);
    return content;
  }

  /**
   * 处理机器人的图片消息
   */
  private String processRobotImg(Map<String, String> requestMap, List<String> args) {
    String mediaId = WechatUploadUtil.fromURLtoWechat(args.get(2), WechatMessageType.image);
    String xml = WechatXMLUtil.toWechatImageXML(requestMap, mediaId);
    return xml;
  }

  /**
   * 处理机人图文消息
   */
  private String processRobotImgtxt(Map<String, String> requestMap, List<String> args) {
    // 获取图文数量
    String count = args.get(1);
    // 获取<![CDATA[]]>中的内容 <![CDATA[获取到的内容]]>
    String content = args.get(3).substring(new String("<![CDATA[").length(), args.get(3).lastIndexOf("]]>")); // 取出中间内容
    return WechatXMLUtil.toWechatImagetxtXML(requestMap, count, content);
  }

  /**
   * 处理机器人音乐消息
   */
  private String processRobotMusic(Map<String, String> requestMap, List<String> args) {
    String mediaId = WechatUploadUtil.fromURLtoWechat(args.get(3), WechatMessageType.thumb);
    return WechatXMLUtil.toWechatMusicXML(requestMap, args.get(0), args.get(1), args.get(2), mediaId);
  }

  /**
   * 处理机器人视频消息
   */
  private String processRobotVideo(Map<String, String> requestMap, List<String> args) {
    String mediaId = WechatUploadUtil.fromURLtoWechat(args.get(2), WechatMessageType.video);
    return WechatXMLUtil.toWechatMusicXML(requestMap, args.get(0), args.get(1), mediaId);
  }
}
